package com.android.forecast.base;

import static android.support.v4.content.ContextCompat.startActivity;
import static java.lang.Thread.sleep;
import static java.security.AccessController.getContext;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.forecast.R;
import com.android.forecast.city.CityFragmentPagerAdapter;
import com.android.forecast.city.CityWeatherFragment;
import com.android.forecast.citymanager.CityManagerActivity;
import com.android.forecast.citymanager.SearchCityActivity;
import com.android.forecast.database.DBManager;
import com.android.forecast.juhe.LocationUtils;
import com.android.forecast.juhe.URLUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView addCityIv, moreIv;
    LinearLayout pointLayout;
    Button up;
    RelativeLayout outLayout;
    VideoView initvideo;
    ImageView ima;
    URLUtils urlutils;
    public static boolean create=false;
    static final String test = "test";
    List<ImageView> imgList;//图标集合
    List<Fragment> fragmentList;
    //    需要显示的城市的集合
    ViewPager mainVp;
    //    ViewPager数据源
    public static List<String> cityList;
    //    ViewPager的页数指数器显示集合
    private CityFragmentPagerAdapter adapter;
    private SharedPreferences pref;
    private int bgNum;
    public static String curcity="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//初始页面
        addCityIv = findViewById(R.id.main_iv_add);//绑定初始页面部件
        moreIv = findViewById(R.id.main_iv_more);
        pointLayout = findViewById(R.id.main_layout_point);
        outLayout = findViewById(R.id.main_out_layout);
        initvideo = findViewById(R.id.videoView);
        ima = findViewById(R.id.imageView);

        //页面内容
        exchangeBg();//背景风格（0，1，2）初始化
        mainVp = findViewById(R.id.main_vp);
        //点击事件
        addCityIv.setOnClickListener(this);
        moreIv.setOnClickListener(this);

        fragmentList = new ArrayList<>();
        cityList = DBManager.queryAllCityName();  //获取数据库包含的城市信息列表
        imgList = new ArrayList<>();

        //开场动画
        if (create == false) {
            ima.setVisibility(View.INVISIBLE);
            initvideo.bringToFront();
            initvideo.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.init0));
            initvideo.setMediaController(new MediaController(this));
            final AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
            alphaAnimation.setDuration(1000);    //深浅动画持续时间
            alphaAnimation.setFillAfter(true);   //动画结束时保持结束的画面
            ima.setAnimation(alphaAnimation);
            initvideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    ima.setVisibility(View.VISIBLE);
                    ima.bringToFront();
                    initvideo.setVisibility(View.INVISIBLE);
                    alphaAnimation.start();
                    initData();
                }
            });
            initvideo.start();
            create = true;
        } else {
            ima.setVisibility(View.INVISIBLE);
            initvideo.setVisibility(View.INVISIBLE);
        }
        //数据初始化
        run();
    }
    public synchronized void run(){
        //初始化位置更新
        if (!(curcity.equals(""))) {//位置更新
            if (cityList.contains(curcity)) {
                cityList.remove(cityList.indexOf(curcity));
            }
            cityList.add(curcity);
        }//基本用不上

        if (cityList.size()==0){
            cityList.add("北京");
        }//填加初始值
        /* 还有一种情况，即搜索界面点击跳转此界面，需要获取数据*/
        try {
            Intent intent = getIntent();
            String city = intent.getStringExtra("city");
            if (!cityList.contains(city) && !city.isEmpty()) {
                cityList.add(city);
            }
        } catch (Exception e) {
            Log.i("animee", "6666666666666");
        }
//     初始化ViewPager页面的方法
        initPager();
        adapter = new CityFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        mainVp.setAdapter(adapter);
//        创建小圆点指示器
        initPoint();
//        设置最后一个城市信息
        mainVp.setCurrentItem(fragmentList.size() - 1);
//        设置ViewPager页面监听
        setPagerListener();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("信息获取失败").setMessage("24小时图获取失败，请查询网络状况或api情况").setPositiveButton("OK", null).show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 粗略位置权限已授予
                initData();
            } else {
                // 粗略位置权限被拒绝
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("获取位置失败").setMessage("获取位置权限失败，请重试").setPositiveButton("OK", null).show();
            }
        }
    }
    private void initData() {
        // 获取经纬度坐标
        // 1 获取位置管理者对象
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 2 通过lm获得经纬调度坐标
        // (参数： provider（定位方式 提供者 通过 LocationManager静态调用），
        // minTime（获取经纬度间隔的最小时间 时时刻刻获得传参数0），
        // minDistance（移动的最小间距 时时刻刻传0），LocationListener（监听）)
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},1);
            return;
            // for ActivityCompat#requestPermissions for more details.
        }
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 20000, 100, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {//自动定位程序
                // 获取经纬度主要方法
                StringBuilder sb = new StringBuilder();
                Geocoder geocoder = new Geocoder(MainActivity.this);
                List<Address> addressList = new ArrayList<Address>();
                try {
                    // 返回集合对象泛型address
                    addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
                    int j = 0;
                    if (addressList.size() > 0) {
                        Address address = addressList.get(0);
                        String city = address.getLocality().substring(0, 2);
                        if (!curcity.equals(city)) {//curcity初始值为空，定位后重置，以此确保定位程序只执行一次·
                            curcity = city;
                            if (cityList.contains(curcity)) {
                                cityList.remove(cityList.indexOf(curcity));//如果原本就存在当前城市，则先移除后添加
                            }
                            cityList.add(curcity);//添加当前城市
                            Intent intent=new Intent();
                            intent.setClass(MainActivity.this,SearchCityActivity.class);//跳转搜索画面
                            intent.putExtra("city",curcity);//将当前城市参数放入intent
                            startActivity(intent);//启动intent跳转
                        }
                    }
                    //bt.setText(new LocationUtils().GetAddr(String.valueOf((int)latitude),String.valueOf((int)longitude)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
                //状态发生改变监听
            }
            @Override
            public void onProviderEnabled(String s) {
                // ProviderEnabled
            }
            @Override
            public void onProviderDisabled(String s) {
                // ProviderDisabled
            }
        });
        Log.d("999999999","test");
    }
    // 换壁纸的函数
    public void exchangeBg(){
        pref = getSharedPreferences("bg_pref", MODE_PRIVATE);
        bgNum = pref.getInt("bg", 0);
        switch (bgNum) {
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
            case 3:
                outLayout.setBackgroundResource(R.mipmap.bg4);
                break;
            case 4:
                outLayout.setBackgroundResource(R.mipmap.bg5);
                break;
        }
    }
    private void setPagerListener() {
        /* 设置监听事件*/
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < imgList.size(); i++) {
                    imgList.get(i).setImageResource(R.mipmap.a1);
                }
                imgList.get(position).setImageResource(R.mipmap.a2);
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initPoint() {
//        创建小圆点 ViewPager页面指示器的函数
        for (int i = 0; i < fragmentList.size(); i++) {
            ImageView pIv = new ImageView(this);
            pIv.setImageResource(R.mipmap.a1);
            pIv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) pIv.getLayoutParams();
            lp.setMargins(0,0,20,0);
            imgList.add(pIv);
            pointLayout.addView(pIv);
        }
        imgList.get(imgList.size()-1).setImageResource(R.mipmap.a2);
    }

    private void initPager() {
        /* 创建Fragment对象，添加到ViewPager数据源当中*/
        for (int i = 0; i < cityList.size(); i++) {
            CityWeatherFragment cwFrag = new CityWeatherFragment();
            Bundle bundle = new Bundle();
            bundle.putString("city",cityList.get(i));
            cwFrag.setArguments(bundle);
            fragmentList.add(cwFrag);
        }
    }
    private void curlocate(String city){
        CityWeatherFragment cwFrag = new CityWeatherFragment();
        Bundle bundle = new Bundle();
        bundle.putString("city",city);
        cwFrag.setArguments(bundle);
        fragmentList.add(cwFrag);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.main_iv_add:
                intent.setClass(this,CityManagerActivity.class);
                break;
            case R.id.main_iv_more:
                intent.setClass(this, MoreActivity.class);
                break;
        }
        startActivity(intent);
    }
    /* 当页面重写加载时会调用的函数，这个函数在页面获取焦点之前进行调用，此处完成ViewPager页数的更新*/
    @Override
    protected void onRestart() {
        super.onRestart();
//        获取数据库当中还剩下的城市集合
        List<String> list = DBManager.queryAllCityName();
        if (list.size()==0) {
            list.add("北京");
        }
        cityList.clear();    //重写加载之前，清空原本数据源
        cityList.addAll(list);
//        剩余城市也要创建对应的fragment页面
        fragmentList.clear();
        initPager();
        adapter.notifyDataSetChanged();
//        页面数量发生改变，指示器的数量也会发生变化，重写设置添加指示器
        imgList.clear();
        pointLayout.removeAllViews();   //将布局当中所有元素全部移除
        initPoint();
        mainVp.setCurrentItem(fragmentList.size()-1);
    }
}
